package captchagenerator;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;

/**
 * Captcha generator.
 *
 * <p>
 *   See <a href="http://isend-blog.appspot.com/2010/03/25/captcha_on_GAE.html">
 *   在GAE上拼接生成图形验证码</a> for more details.
 * </p>
 * 
 * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
 * @version 1.0.0.0, Aug 26, 2010
 */
public final class Main {

    public static void main(String[] args) throws IOException {
        final int width = 130, height = 200;
        final BufferedImage bufferedImage =
                new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        final Graphics graphics = bufferedImage.getGraphics();
        for (int i = 0; i < 10; i++) {
            graphics.setColor(getRandColor(200, 250));
            graphics.fillRect(0, i * 20, width, (i + 1) * 20);
        }

        graphics.setFont(new Font("Times New Roman", Font.PLAIN, 18));
        final Random random = new Random();

        graphics.setColor(getRandColor(160, 200));
        for (int i = 0; i < 15000; i++) {
            final int x = random.nextInt(width);
            final int y = random.nextInt(height);
            graphics.drawLine(x, y, x, y);
        }

        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                graphics.setColor(getRandColor(20, 130));
                graphics.drawString(String.valueOf(j), j * 13 + 3, i * 20 + 16);
            }
        }

        graphics.setColor(getRandColor(200, 250));
        for (int i = 0; i < 2000; i++) {
            final int x = random.nextInt(width - 12);
            final int y = random.nextInt(height);
            graphics.drawLine(x, y, x, y);
        }

        graphics.dispose();
        final OutputStream outputStream = new FileOutputStream("captcha.png");

        ImageIO.write(bufferedImage, "png", outputStream);
        outputStream.close();
    }

    private static Color getRandColor(final int fc, final int bc) {
        final Random random = new Random();
        final int r = fc + random.nextInt(bc - fc);
        final int g = fc + random.nextInt(bc - fc);
        final int b = fc + random.nextInt(bc - fc);

        return new Color(r, g, b);
    }
}
